<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入用户的姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="用户名" show-overflow-tooltip align="center" prop="username"/>
      <el-table-column label="昵称" show-overflow-tooltip align="center" prop="nickName"/>
      <el-table-column label="血氧平均(近一个月)" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.physicalData && scope.row.physicalData.avgBloodOxygen != null" type="text"
                     @click="openSpecificData(scope.row, 'bloodOxygen')">{{
              scope.row.physicalData.avgBloodOxygen.toFixed(2)
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="血压平均(近一个月)" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.physicalData && scope.row.physicalData.avgSbp != null && scope.row.physicalData.avgDbp != null"
            type="text" @click="openSpecificData(scope.row, 'bloodPressure')">{{
              scope.row.physicalData.avgSbp.toFixed(0) + '/' + scope.row.physicalData.avgDbp.toFixed(0)
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="心率平均(近一个月)" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.physicalData && scope.row.physicalData.avgHeartrate != null"
            type="text" @click="openSpecificData(scope.row, 'heartrate')">{{
              scope.row.physicalData.avgHeartrate.toFixed(2)
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="深睡/浅睡平均(近一个月)" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.physicalData && scope.row.physicalData.avgDeepSleep != null && scope.row.physicalData.avgLightSleep != null"
            type="text" @click="openSpecificData(scope.row, 'sleep')">{{
              scope.row.physicalData.avgDeepSleep.toFixed(2) + '/' + scope.row.physicalData.avgLightSleep.toFixed(2)
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="计步平均(近一个月)" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.physicalData && scope.row.physicalData.avgStep != null"
            type="text" @click="openSpecificData(scope.row, 'stepCount')">{{
              scope.row.physicalData.avgStep.toFixed(0)
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="最近一次评分" align="center">
        <template slot-scope="scope">
          {{
            scope.row.physicalData && scope.row.physicalData.lastScore != null ? scope.row.physicalData.lastScore : ''
          }}
        </template>
      </el-table-column>
      <el-table-column label="最近一次评分时间" align="center">
        <template slot-scope="scope">
          {{
            scope.row.physicalData && scope.row.physicalData.lastScoreTime != null ? scope.row.physicalData.lastScoreTime : ''
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['appuser:score:add']"
          >打分
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生给app用户打的评分对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分数" prop="score">
          <el-input-number max="100" min="0" precision="2" v-model="form.score" placeholder="请输入分数（满分100）"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="specificEchartTitle" :visible.sync="specificEchartOpen" width="800px"
               @close="specificEchartClose" append-to-body :modal-append-to-body="false">
      <div v-loading="specificEchartLoading" id="specificEchartDiv" :style="echartsStyle"></div>
    </el-dialog>
  </div>
</template>

<script>
import {listUserAndData, addScore, appuserSpecificData} from "@/api/appuser/score";
import {dateFormat} from "@/utils/dateUtils";
import echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from "@/utils/resize";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  name: "Score",
  data() {
    return {
      // 遮罩层
      loading: true,
      specificEchartLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户列表数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //各类数据的弹窗
      specificEchartOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: null,
        startTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        score: [
          {required: true, message: "分数不能为空", trigger: "blur"}
        ]
      },
      echartsStyle: {
        "height": "480px"
      },
      //各类数据图表
      specificEchart: null,
      specificEchartTitle: ''
    };
  },
  created() {
    //设置要查询的数据的日期范围
    let tempDate = new Date();
    tempDate.setMonth(tempDate.getMonth() - 1);
    this.queryParams.startTime = dateFormat(tempDate, "yyyy-MM-dd HH:mm:ss");
    this.getList();
  },
  methods: {
    /** 查询医生给app用户打的评分列表 */
    getList() {
      this.loading = true;
      listUserAndData(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        creator: null,
        createTime: null,
        dataStartTime: null,
        dataEndTime: null,
        score: null,
        mdUserId: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.mdUserId = row.id;
      this.form.dataStartTime = this.queryParams.startTime;
      this.form.dataEndTime = dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
      this.open = true;
      this.title = "为用户的健康状况评分";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addScore(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    //打开血氧弹窗
    openSpecificData(row, dataType) {
      //打开弹窗
      this.specificEchartOpen = true;
      this.specificEchartLoading = true;
      //初始化图表
      let param = {
        "username": row.username,
        "startTime": this.queryParams.startTime,
        "dataType": dataType
      };
      appuserSpecificData(param).then(response => {
        let list = response.data;
        //legend灵活配置
        let legendData = [];
        //最大最小值灵活配置
        let ymin = null;
        let ymax = null;
        //数据灵活配置
        let echartsData = [];
        let echartsData2 = [];
        let echartsData3 = [];
        switch (dataType) {
          case "bloodOxygen":
            this.specificEchartTitle = "血氧(近一个月)";
            ymin = 90;
            ymax = 100;
            echartsData = list.map(item => {
              return [item.timeBegin, item.bloodoxygen];
            });
            break;
          case "heartrate":
            this.specificEchartTitle = "心率(近一个月)";
            ymin = 40;
            ymax = 140;
            echartsData = list.map(item => {
              return [item.timeBegin, item.heartrate];
            });
            break;
          case "sleep":
            this.specificEchartTitle = "睡眠(近一个月)";
            ymin = 0;
            legendData = ["深睡", "浅睡", "总睡眠"];
            for (let item of list) {
              echartsData.push([item.timeBegin, item.deepSleep])
              echartsData2.push([item.timeBegin, item.lightSleep])
              echartsData3.push([item.timeBegin, item.totalSleep])
            }
            break;
          case "stepCount":
            this.specificEchartTitle = "运动步数(近一个月)";
            ymin = 0;
            echartsData = list.map(item => {
              return [item.timeBegin, item.value];
            });
            break;
          case "bloodPressure":
            this.specificEchartTitle = "血压(近一个月)";
            ymin = 60;
            ymax = 140;
            legendData = ["收缩压", "舒张压"];
            for (let item of list) {
              echartsData.push([item.timeBegin, item.sbp])
              echartsData2.push([item.timeBegin, item.dbp])
            }
            break;
          default:
            break;
        }
        this.specificEchart = echarts.init(document.getElementById("specificEchartDiv"));
        //图表配置项
        let option = {
          tooltip: {
            show: true,
            formatter: params => {
              let arr = params.value;
              return `<i class="el-icon-edit" style="color: orangered"></i>${arr[1]}</br>${arr[0]}`
            }
          },
          legend: {
            data: legendData
          },
          xAxis: {
            type: 'time',
            min: this.queryParams.startTime,
            max: dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss"),
            axisLabel: {
              formatter: (value, index) => {
                return dateFormat(new Date(value), "MM-dd")
              }
            }
          },
          yAxis: {
            type: 'value',
            min: ymin,
            max: ymax
          },
          series: [
            {
              data: echartsData,
              type: 'line',
              smooth: true
            }
          ]
        };
        //若一个图表有多类数据，series配置不一样
        if (legendData.length) {
          option.series[0].name = legendData[0];
        }
        if (echartsData2.length) {
          option.series.push({
            name: legendData[1],
            data: echartsData2,
            type: 'line',
            smooth: true
          })
        }
        if (echartsData3.length) {
          option.series.push({
            name: legendData[2],
            data: echartsData3,
            type: 'line',
            smooth: true
          })
        }
        this.specificEchart.setOption(option)
        this.specificEchartLoading = false;
      });
    },
    specificEchartClose() {
      if (!this.specificEchart) {
        return
      }
      this.specificEchart.dispose()
      this.specificEchart = null
    }
  }
};
</script>
